package com.takeaway.servlet;

import com.takeaway.const_.Const;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 后台赖骏
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        //获取请求
        String uri = req.getRequestURI();
        //获取最后一段的方法名
        int index = uri.lastIndexOf('/');
        String methodName = uri.substring(index+1);
        try {
            Method method = this.getClass()
                    .getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            req.setAttribute("msg", Const.ILLEGAL_INPUT_MSG);
            try {
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            } catch (ServletException | IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
